package com.bifang.common.util;

import static com.google.common.collect.Iterables.getFirst;

import com.bifang.common.exception.AppException;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

/** 业务参数校验 */
public class ValidateUtils {
    private static final Validator VALIDATOR =
            Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> void validate(T object) {
        // 执行验证
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(object);
        // 如果有验证信息，则取出包装成异常返回
        ConstraintViolation<T> constraintViolation = getFirst(constraintViolations, null);
        if (constraintViolation != null) {
            throw new AppException(constraintViolation.getMessage());
        }
    }
}
